import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by msi on 2018/6/6 0006.
 * 抓取城市列表
 */
public class CitiesPageProcess implements PageProcessor {
    // 抓取网站的相关配置，包括编码、抓取间隔、重试次数等
    private Site site = Site.me().setRetryTimes(3).setSleepTime(100);
    private static int count = 1;

    public void process(Page page) {
        //获取城市url
        Pattern patternUrl = Pattern.compile("[a-zA-z]+://[^\\s]*");

        //取出标签内的值
        Pattern patternText = Pattern.compile(">.*?<");
        List<String> cities = page.getHtml().xpath("//*[@id=\"c01\"]").$("a").all();
        for (String city : cities) {
            Matcher matcherUrl = patternUrl.matcher(city);
            Matcher matcherText = patternText.matcher(city);
            if (matcherUrl.find() && matcherText.find())
                System.out.println(count + "|" + matcherText.group().substring(1, matcherText.group().length() - 1) + "|" + matcherUrl.group().substring(0, matcherUrl.group().length() - 1));
            count++;
        }
    }

    public Site getSite() {
        return site;
    }

    public static void main(String[] args) {
        long startTime, endTime;
        System.out.println("开始爬取...");
        startTime = System.currentTimeMillis();
        Spider.create(new CitiesPageProcess()).addUrl("http://www.fang.com/SoufunFamily.htm").thread(1).run();
        endTime = System.currentTimeMillis();
        System.out.println("爬取结束，耗时约" + ((endTime - startTime) / 1000) + "秒，抓取了" + count + "条记录");
    }
}
